<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkEmployee\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkMessage\Event\MessageReceivedEvent;
use Psr\Container\ContainerInterface;

/**
 * 最后联系时间.
 *
 * @Listener
 */
class LastMessageTimeRawListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var WorkEmployeeContract;
     */
    protected $workEmployeeService;

    /**
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @var array
     */
    private $message;

    public function listen(): array
    {
        return [
            MessageReceivedEvent::class,
        ];
    }

    /**
     * @param MessageReceivedEvent $event
     */
    public function process(object $event)
    {
        try {
            $corpId = (int) $event->corpId;
            $messages = $event->messages;
            $this->logger = make(StdoutLoggerInterface::class);
            $this->workContactService = make(WorkContactContract::class);
            $this->workEmployeeService = make(WorkEmployeeContract::class);
            $this->workContactEmployeeService = make(WorkContactEmployeeContract::class);

            foreach ($messages as $msg) {
                // 排除群聊信息,撤回信息，切换企业日志
                if ((int) $msg['tolist_type'] === 2 || (int) $msg['action'] !== 0) {
                    return [];
                }
                $contactId = 0;
                $employeeId = 0;
                $this->logger->error('最后联系时间222' . $msg['tolist'][0]);
                // 发送人
                if ($this->isContact($msg['from'])) {
                    $contact = $this->workContactService->getWorkContactByWxExternalUserId($msg['from'], ['id']);
                    ! empty($contact) && $contactId = $contact['id'];
                } else {
                    $employee = $this->workEmployeeService->getWorkEmployeeByWxUserId($msg['from'], ['id']);
                    ! empty($employee) && $employeeId = $employee['id'];
                }
                // 接收人
                if ($this->isContact($msg['raw']['tolist'][0])) {
                    $contact = $this->workContactService->getWorkContactByWxExternalUserId($msg['raw']['tolist'][0], ['id']);
                    ! empty($contact) && $contactId = $contact['id'];
                } else {
                    $employee = $this->workEmployeeService->getWorkEmployeeByWxUserId($msg['raw']['tolist'][0], ['id']);
                    ! empty($employee) && $employeeId = $employee['id'];
                }
                if ($contactId <= 0 || $employeeId <= 0) {
                    return [];
                }
                // 最后联系时间
                $time = substr($msg['msg_time'], 0, 10);
                $date = date('Y-m-d H:i:s', (int) $time);
                $this->workContactEmployeeService->updateWorkContactEmployeeByOtherIds($employeeId, $contactId, ['last_message_time' => $date]);
            }
        } catch (\Exception $e) {
            $this->logger->error(sprintf('[最后联系时间]失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
        return [];
    }

    private function isContact(string $from): bool
    {
        $fromPrefix = substr($from, 0, 2);
        return in_array($fromPrefix, ['wo', 'wm']);
    }
}
